package com.ksyun.campus.client;

import cn.hutool.json.JSONUtil;
import com.ksyun.campus.client.constant.api.DataServerApi;
import com.ksyun.campus.client.constant.api.MetaServerApi;
import com.ksyun.campus.client.domain.MetaServer;
import com.ksyun.campus.client.domain.MetaWrite;
import com.ksyun.campus.client.domain.ReplicaData;
import com.ksyun.campus.client.util.FSHttpUtils;
import com.ksyun.campus.client.util.ZkUtil;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;

@Slf4j
public class FSOutputStream extends OutputStream {
    private String dataNode;

    private String fileSystem;

    private String path;

    private List<ReplicaData> list;

    private int totalSize = 0;

    public FSOutputStream(String dataNode, String fileSystem, String path) {
        this.dataNode = dataNode;
        this.fileSystem = fileSystem;
        this.path = path;
    }

    @Override
    public void write(int b) throws IOException {
        write(new byte[]{(byte) b}, 0,1);
    }

    @Override
    public void write(byte[] b) throws IOException {
        write(b, 0, b.length);
    }

    @Override
    public void write(byte[] b, int off, int len) {
        FSHttpUtils.write(dataNode + DataServerApi.WRITE, b, path, fileSystem, off, len);
        totalSize += len;
    }

    /**
     * 关闭之后 更新元数据
     */
    @Override
    public void close()  {
        FSHttpUtils.HttpResult result = FSHttpUtils.get(dataNode + DataServerApi.CLOSE, path, fileSystem);
        //关闭流后 得到三个副本信息
        list = JSONUtil.toList(result.content, ReplicaData.class);
        log.info("关闭流~,总写入{}",totalSize);
        MetaServer metaMater = ZkUtil.getMetaMaster();
        String url = metaMater.getIp() + ":" + metaMater.getPort() + MetaServerApi.WRITE;
        MetaWrite metaWrite = new MetaWrite();
        metaWrite.setPath(path);
        metaWrite.setReplicaData(list);
        metaWrite.setSize(totalSize);
        //更新元数据
        FSHttpUtils.post(url, null, fileSystem, metaWrite);
    }
}
